from flask import render_template, current_app, session, request, jsonify

from info import constants
from info.models import User, News, Category
from info.modules.index import index_blue
from info.utils.response_code import RET


@index_blue.route('/')
def index():
    # 获取session，判断用户是否登录
    user_id = session.get('user_id')
    user = None # type User
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    try:
        #
        click_datas = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    click_data_list = []
    for click_data in click_datas:
        click_data_list.append(click_data.to_basic_dict())
    try:
        #
        category_datas = Category.query.filter().all()
    except Exception as e:
        current_app.logger.error(e)
    category_data_list = []
    for click_data in category_datas:
        category_data_list.append(click_data.to_dict())


    data = {
        'user_info': user.to_dict() if user else None,
        'click_news':click_data_list,
        'category':category_data_list
    }

    return render_template('news/index.html',data=data)

# 第一次请求时，会自动发送这个请求，后面若是
@index_blue.route("/favicon.ico")
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blue.route('/testing')
def testing():
    # 测试代码
    # redis_store.set('name', 'csx')
    # redis_store.set('gouqiang', 'gouqiang')
    #
    # res = redis_store.hget('student','age')
    # print(res)
    # 添加日志
    # logging.debug("This is a debug log.")
    # logging.info("This is a info log.")
    # logging.warning("This is a warning log.")
    # logging.error("This is a error log.")
    # logging.critical("This is a critical log.")
    # 测试
    # current_app.logger.debug('debug')
    # #
    # current_app.logger.info('info')
    # # 警告
    # current_app.logger.warning('warning')
    # # 错误
    # current_app.logger.error('error')
    # # 重大错误
    # current_app.logger.critical('critical')
    return 'index'

@index_blue.route('/newlist')
def show_new_list():
    """

    :return:
    """
    params = request.args
    # 每一页的数量
    per_page = params.get('per_page',constants.HOME_PAGE_MAX_NEWS)
    # 当前的页数
    page = params.get('current_page','1')
    # 新闻分类id
    category_id = params.get('current_page_id','1')

    try:
        per_page = int(per_page)
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filter = [News.status == 0]
    if category_id != '1':
        filter.append(News.category_id == category_id)
    # 查询数据，根据时间进行排序，分页
    try:
        page_data = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page)
        # 获取数据
        # 每一页的数据
        items = page_data.items
        # 当前页数
        now_page = page_data.page
        # 总页数
        sum_page = page_data.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    return jsonify(errno=RET.OK, errmsg="OK", totalPage=sum_page, currentPage=now_page, newsList=news_list, cid=category_id)

